package com.github.permissiondog.cancanpbackend.servlet;

import com.github.permissiondog.cancanpbackend.model.User;
import com.github.permissiondog.cancanpbackend.request.UserCreateRequest;
import com.github.permissiondog.cancanpbackend.request.UserDeleteRequest;
import com.github.permissiondog.cancanpbackend.request.UserModifyRequest;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.response.UserResponse;
import com.github.permissiondog.cancanpbackend.response.UsersResponse;
import com.github.permissiondog.cancanpbackend.service.UserService;
import org.apache.ibatis.exceptions.PersistenceException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "AdminUserServlet", value = "/admin/user")
public class AdminUserServlet extends BaseServlet {
    /**
     * 获取用户列表
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        var username = request.getParameter("username");
        if (username == null) {
            var users = UserService.getInstance().getUsers();
            json(response, UsersResponse.builder().ok(true).users(users).build());
        } else {
            var user = UserService.getInstance().getUserByUsername(username);
            json(response, UserResponse.builder().ok(true).user(user).build());
        }
    }

    /**
     * 创建用户
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        UserCreateRequest body = bind(request, response, UserCreateRequest.class);
        if (body == null)   return;

        try {
            UserService.getInstance().createUser(body.username, body.nickname, body.password, body.department, body.role);
        } catch (PersistenceException e) {
            json(response, BaseResponse.builder().ok(false).msg("创建失败").build());
            return;
        }
        json(response, BaseResponse.builder().ok(true).build());

    }

    /**
     * 修改用户
     */
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        var body = bind(req, resp, UserModifyRequest.class);
        if (body == null)   return;

        try {
            var user = UserService.getInstance().getUserById(body.userId);
            if (user == null) {
                json(resp, BaseResponse.builder().ok(false).msg("用户 ID 不存在").build());
                return;
            }
            user.setNickname(body.nickname);
            user.setDepartment(body.department);
            user.setRole(body.role);
            UserService.getInstance().modifyUser(user);
            if (body.password != null && !"".equals(body.password)) {
                UserService.getInstance().changePassword(body.userId, body.password);
            }
            json(resp, UserResponse.builder().ok(true).user(user).build());
        } catch (Exception e) {
            json(resp, BaseResponse.builder().ok(false).error(e.getMessage()).msg("修改失败").build());
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        var body = bind(req, resp, UserDeleteRequest.class);
        if (body == null)   return;

        try {
            var user = UserService.getInstance().getUserById(body.userId);
            if (user == null) {
                json(resp, BaseResponse.builder().ok(false).msg("用户 ID 不存在").build());
                return;
            }
            UserService.getInstance().deleteUser(body.userId);
            json(resp, BaseResponse.builder().ok(true).build());
        } catch (Exception e) {
            json(resp, BaseResponse.builder().ok(false).error(e.getMessage()).msg("删除失败").build());
        }
    }
}
